import React from 'react';
import { Layout, Breadcrumb, Icon, Tag, Button, Table, Checkbox, Input, Select, Form, Pagination, message, TreeSelect } from 'antd';
import { Link ,hashHistory} from 'react-router';
import $ from 'jquery';
import Config from '../../common/config';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token')

class RegForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: false, //菜单折叠状态
            mode: 'inline', //菜单显示模式，垂直 or 行内
            productlist: [],//全部商品列表
            productcount: 0,//全部商品条数
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            keyword: undefined,//关键字
            selectproductid: [],//选中的商品ID
            categoryid: undefined,//分类
            selectedRowKeys:[],//选中行
            selectedRows:[],//选中行
            branchlist:[],//分类列表
            proid:this.props.params.proId,//编辑时 产品id
        }
    }

    componentDidMount() {
        console.log(this.props.params)


        this.GetProguctList();
        this.getbranch();
    }

    //商品列表
    GetProguctList() {
        var me=this;
        $.ajax({
            url: `${config.integratedBack}/com/findComList`,
            type: "get",
            data: {
                inKey:this.state.keyword,
                categoryId:this.state.categoryid,
                page:this.state.pageindex,
                pageSize:this.state.pagesize
            },
            success: function (d) {
                console.log(d);
                if(d.code==200){
                    me.setState({
                        productlist:d.list.rows,
                        productcount:d.list.count
                    })
                }
            }
        })
    }
    //获取分类
    getbranch(){
        var me=this;
        $.ajax({
            url: `${config.JuseProduct}/categories/getCategoriesTree`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: function (d) {
                console.log(d);
                if(d.code==200){
                    var treeData=[];
                    for(var i=0;i<d.data.length;i++){
                        treeData[i]={
                            label: d.data[i].categoryName,
                            value: d.data[i].categoryId,
                            children:d.data[i].son
                        }
                        if(d.data[i].son.length>0){
                            for(var k=0;k<d.data[i].son.length;k++){
                                treeData[i].children[k]={
                                    label: d.data[i].son[k].categoryName,
                                    value: d.data[i].son[k].categoryId,
                                }
                            }
                        }

                    }
                    me.setState({
                        branchlist:treeData
                    })
                }
            }
        })

    }
    //增加商品
    addIndexGoods(){
        console.log(this.state.productlist.length)
        var selectedRows=[];
        for(var i=0;i<this.state.selectedRowKeys.length;i++){
            if(this.state.selectedRowKeys[i]>this.state.productlist.length){
                break;
            }else{
                selectedRows.push(this.state.productlist[this.state.selectedRowKeys[i]])
            }
        }
        console.log(selectedRows)
        var proId=[];
        for(var i=0;i<selectedRows.length;i++){
            proId.push({productId:selectedRows[i].productId})

        }
        if(proId.length<=0){
            alert('请选择需要添加的商品')
        }else {
            $.ajax({
                url: `${config.integratedBack}/com/addCommodity`,
                type: "post",
                data: {
                    commid:JSON.stringify(proId)
                },
                success: res => {
                    console.log(res);
                    if (res.code === 200) {
                        alert('添加成功！！');
                        hashHistory.push('indexGoods');
                    }
                }
            });
        }
    }
    //编辑商品
        editIndexGoods(){
            var proId=[];
            for(var i=0;i<this.state.selectedRows.length;i++){
                proId.push({productId:this.state.selectedRows[i].productId})

            }
            if(proId.length<=0){
                alert('请选择需要编辑的产品')
            }else if(proId.length>1){
                alert('一次只能编辑一个商品')
            }else if(proId.length==1){
                $.ajax({
                    url: `${config.integratedBack}/com/replaceCommodity`,
                    type: "get",
                    data: {
                        id:this.state.proid,
                        nowId:proId[0].productId
                    },
                    success: res => {
                        console.log(res);
                        if (res.code === 200) {
                            alert('保存成功！！');
                            hashHistory.push('indexGoods');
                        }
                    }
                });
            }
        }
    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex,
        }, () => {
            this.GetProguctList();
        });
    }

    //选择分类
    changeCategory(value) {
        this.setState({
            categoryid: value
        })
    }
    //重置
    ResetBtn() {
        const form = this.props.form;
        form.resetFields();
        this.setState({
            pageindex: 1,
            categoryid: undefined,
            keyword: undefined
        }, () => {
            this.GetProguctList();
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                this.setState({
                    selectedRowKeys:selectedRowKeys,
                    selectedRows:selectedRows
                });
            },
            getCheckboxProps: record => ({
                disabled: record.createtime ==='总计', // Column configuration not to be checked
            }),
        };
        const columns = [
            {
                title: '序号',
                dataIndex: 'productId',
                width: '14%',
            },
            {
                title: '药品名称',
                dataIndex: 'productName',
                width: '14%',
            },
            {
                title: '药品图片',
                dataIndex: '',
                width: '14%',
                render: (text, record) => {
                    return <img src={record.imageUrl + record.listImage} />
                }
            },
            {
                title: '通用名',
                dataIndex: 'generalName',
                width: '14%',
            },
            {
                title: '规格',
                dataIndex: 'formula',
                width: '14%',
            },
            {
                title: '品牌',
                dataIndex: 'brandName',
                width: '14%',
            },
            {
                title: '生产厂家',
                dataIndex: 'manufacturer',
                width: '14%',
            },
        ];
        return (
            <Form>
                <div className='goods-label' style={{ minWidth: 1250 }}>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>全部商品管理</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>

                        <div className='member-content-Search clearfix'>
                            <div className='addetd'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_Inkey')(
                                            <Input className='addetd-a-r' addonBefore="序号/药品名称/通用名/品牌" placeholder="请输入" onChange={(e)=>this.setState({keyword:e.target.value})}/>
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd-bb indtner'>
                                <InputGroup compact>
                                    <Input addonBefore="分 类" />
                                    <TreeSelect
                                        style={{ width: 210 }}
                                        value={this.state.categoryid}
                                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                        treeData={this.state.branchlist}
                                        placeholder="请选择"
                                        treeDefaultExpandAll
                                        onChange={(value) => this.changeCategory(value)}
                                    />
                                </InputGroup>
                            </div>
                            <Button type="primary" className='member-button' icon="search" onClick={this.GetProguctList.bind(this)}>搜索</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={this.ResetBtn.bind(this)}>重置</Button>
                        </div>
                        <div>
                            <Table
                                rowSelection={rowSelection}
                                columns={columns}
                                dataSource={this.state.productlist}
                                pagination={false}
                                bordered
                                className='allgoods-table'
                            />
                        </div>
                        <div className='goods-label-let'>
                            <div  style={{textAlign:'center',paddingTop:'20px',paddingBottom:'20px'}}>
                                {/*<Button className='goods-label-table-app' width={160} icon="plus" onClick={() => { window.location.hash = "/goodsdetail/0"; }}>发布新商品</Button>*/}
                                {/*<Button className='goods-label-table-app' width={105} icon="download" onClick={this.ChangeProductStateManage.bind(this, 2, '商品下架')}>商品下架</Button>*/}
                                {/*<Button className='goods-label-table-app' width={105} icon="upload" onClick={this.ChangeProductStateManage.bind(this, 1, '商品上架')}>商品上架</Button>*/}
                                <Button  width={105} onClick={()=>{hashHistory.push('indexGoods')}}>取消</Button>
                                {
                                    this.state.proid==0?
                                        <Button  width={105} type="primary" style={{color:'#fff',marginLeft:'20px'}} onClick={this.addIndexGoods.bind(this)}>确认添加</Button>
                                        :<Button  width={105} type="primary" style={{color:'#fff',marginLeft:'20px'}} onClick={this.editIndexGoods.bind(this)}>保存编辑</Button>

                                }
                            </div>
                            <div className="floor-ppagi">
                                {
                                    this.state.productcount == 0 ?
                                        <p className="floor-ppagip">
                                            共{this.state.productcount}条记录
                                        </p> :
                                        <p className="floor-ppagip">
                                            当前显示
                                            {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                            {this.state.pagesize * this.state.pageindex < this.state.productcount ? this.state.pagesize * this.state.pageindex : this.state.productcount}条记录，
                                            共{this.state.productcount}条记录
                                        </p>
                                }
                                <Pagination current={this.state.pageindex} total={this.state.productcount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                            </div>
                        </div>
                    </div>
                </div>
            </Form>
        )
    }
}

const ChooseIndexGoods = Form.create()(RegForm);
export default ChooseIndexGoods;